package com.hnkywl.sts.service.sfgl;

import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.dao.sfgl.HzkxDao;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by HL on 2015/9/22.
 */
@Service
public class HzkxService {
    private GsjgDao gsjgDao;
    private HzkxDao hzkxDao;

    @Transactional
    public String findAllHzkx(Date hzkxStart, Date hzkxEnd, String bm, String ybm, String sbgsMc, Long sbgsId, String gldwMc, String zt, int pageNo, int pageSize) {
        Long nbgsIds = null;
        if (sbgsId != null && sbgsMc.equals(gsjgDao.get(sbgsId).getJc())) {
            nbgsIds = nbgsIds;
        }
        Page<Sfk> hzkxPage = this.hzkxDao.findHzkxList(hzkxStart, hzkxEnd, bm, ybm, sbgsMc, nbgsIds, gldwMc, zt, pageNo, pageSize);
        List<Sfk> hzkxList = hzkxPage.getResult() == null ? new ArrayList<Sfk>() : hzkxPage.getResult();
        String hzkxJson = BaseUtils.fetchCollectionToJson(hzkxList, "id", "bm", "sfkrq", "sfklx", "gldw.qc", "kxyt.z", "kxsy.z", "fkfs.z", "sfje", "pjlx.z", "kxlx", "sbgs.jc", "sbr.xm", "bz", "zt", "shrq", "khfksj", "sfhz", "pjhm", "fplx", "nbhzsfk.bm");
        return "{\"total\":" + hzkxPage.getTotalCount() + ",\"rows\":[" + hzkxJson + "]}";
    }

    @Transactional
    public void changHzkxStatus(Long sfkId, String shjg) {
        Sfk temp = this.hzkxDao.get(sfkId);
        if (StringUtils.equals("0", shjg)) {
            // 审核通过
            temp.setZt("ytz");
        } else {
            // 如果不通过删除，把金额加回原单据
            temp.setDeleted(1);
            temp.setBz("【物流金融划转非计划现货，审核不通过】");
            Sfk ysfk = temp.getNbhzsfk();
            ysfk.setYe(ysfk.getYe() + temp.getSfje());
            if (null != ysfk.getNbhzSfkList() && ysfk.getNbhzSfkList().size() < 2) {
                ysfk.setSfhz("0");
            }
            this.hzkxDao.save(ysfk);
        }
        this.hzkxDao.save(temp);
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }

    @Autowired
    public void setHzkxDao(HzkxDao hzkxDao) {
        this.hzkxDao = hzkxDao;
    }

}
